package com.changjie.wang.doc;

import com.changjie.wang.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class EsClient_CreateDoc_Batch {
    /**
     * 批量插入文档数据
     * @param args
     */
    public static void main(String[] args) {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        try {
            //批量插入数据
            BulkRequest request = new BulkRequest();
            request.add(new IndexRequest().index("user").id("001").source(XContentType.JSON,"name","刘德华","sex","男","age",60));
            request.add(new IndexRequest().index("user").id("002").source(XContentType.JSON,"name","郭富城","sex","男","age",56));
            request.add(new IndexRequest().index("user").id("003").source(XContentType.JSON,"name","张学友","sex","男","age",60));
            request.add(new IndexRequest().index("user").id("004").source(XContentType.JSON,"name","黎明","sex","男","age",54));
            BulkResponse response = esClient.bulk(request,RequestOptions.DEFAULT);
            System.out.println(response.getTook());
            BulkItemResponse[] items = response.getItems();
            for (BulkItemResponse item : items) {
                System.out.println(item);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭ES客户端
            try {
                esClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
